package cn.brondfish.icedfish.framework.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import java.io.IOException;

import cn.brondfish.icedfish.framework.config.BF_APPConfigEntity;

public class BF_ConfigUtil {
    private static final String ERROR_TAG = "BF_ConfigUtil->Update AppConfig Error";
    private static BF_ConfigUtil bfConfigUtil;
    private BF_APPConfigEntity appConfig;
    private BF_PropertiesUtil<BF_APPConfigEntity> util;
    private Context app_context;
    public BF_ConfigUtil(Context context) {
        util = new BF_PropertiesUtil<>(context, BF_APPConfigEntity.APP_CONFIG_FILE,BF_APPConfigEntity.class);
        try {
            appConfig = util.parsePropertiesToObj();
            this.app_context = context;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        }
    }

    public static BF_ConfigUtil getInstance(Context context) {
        if (bfConfigUtil == null) {
            synchronized (BF_ConfigUtil.class){
                if (bfConfigUtil == null) {
                    bfConfigUtil = new BF_ConfigUtil(context);
                }
            }
        }
        return bfConfigUtil;
    }

    public void update() {
        try{
            if(appConfig == null){
                PackageInfo package_info = app_context.getApplicationContext().getPackageManager().
                        getPackageInfo(app_context.getPackageName(), 0);
                long appVersionCode = package_info.getLongVersionCode();
                appConfig = new BF_APPConfigEntity();
                appConfig.setCfg_version(String.valueOf(appVersionCode));
                util.updateProperties(appConfig);
            }else {
                util.updateProperties(appConfig);
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(ERROR_TAG,e.getMessage());
            throw new RuntimeException(e);
        } catch (IOException e) {
            Log.e(ERROR_TAG,e.getMessage());
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            Log.e(ERROR_TAG,e.getMessage());
            throw new RuntimeException(e);
        }

    }

    public boolean haveConfig(){
        return appConfig != null;
    }

    public BF_APPConfigEntity getAppConfig() {
        return appConfig;
    }
}
